import { useEffect } from 'react'

import { orgUpdatePasswordApi } from '@/api/app'
import AekForm from '@/components/AekForm'
import AekModal, { PromiseThen } from '@/components/AekModal'
import { REGEXP_PASSWORD } from '@/utils/constants'
import { requestWithTry } from '@/utils/request'

const ChangeModal = ({ row = {} }) => {
  const [form] = AekForm.useForm()
  const { organizationId } = row

  useEffect(() => {
    if (!organizationId) return
    form.setFieldsValue({
      ...row,
    })
  }, [organizationId])

  /** @type {import("@/components/AekForm").FormDataProps[]} */
  const formData = [
    {
      field: 'password',
      label: '新密码',
      formItemProps: {
        rules: [
          { required: true },
          {
            pattern: REGEXP_PASSWORD,
            message: '6-16位，大、小写字母、数字、特殊字符（,.-+_@!?#*%）任意三种类型组合',
          },
        ],
      },
      component: { name: 'InputPassword' },
    },
    {
      field: 'confirmedPassword',
      label: '确认密码',
      formItemProps: {
        rules: [
          { required: true },
          {
            pattern: REGEXP_PASSWORD,
            message: '6-16位，大、小写字母、数字、特殊字符（,.-+_@!?#*%）任意三种类型组合',
          },
        ],
      },
      component: { name: 'InputPassword' },
    },
  ]

  const onOk = async () => {
    const values = await form.validateFields()
    const params = {
      organizationId,
      ...values,
    }
    await requestWithTry(orgUpdatePasswordApi, params)
  }
  return (
    <AekModal title='修改密码' width={500} onOk={onOk}>
      <AekForm form={form} formData={formData} />
    </AekModal>
  )
}

ChangeModal.PromiseThen = PromiseThen

export default ChangeModal
